package com.ckm.config;

import com.ckm.datasource.DynamicMongoFactory;
import com.ckm.properties.DynamicMongoProperties;
import com.ckm.provider.DynamicMongoSourceProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
@EnableAspectJAutoProxy(exposeProxy = true)
public class MongoConfig {

    private final DynamicMongoProperties properties;

    @Bean
    @ConditionalOnMissingBean
    public DynamicMongoFactory dynamicMongoFactory(List<DynamicMongoSourceProvider> providers){
        DynamicMongoFactory dynamicMongoFactory = new DynamicMongoFactory(providers);
        SimpleMongoClientDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(properties.getUri());
        dynamicMongoFactory.setDefaultTargetMongoDatabaseFactory(factory);
        return dynamicMongoFactory;
    }


    @Bean
    @ConditionalOnMissingBean
    public MongoTemplate mongoTemplate(DynamicMongoFactory dynamicMongoFactory){
        
        return new MongoTemplate(dynamicMongoFactory);
    }
}
